import 'package:beautiful_demo/common/manager/user.dart';
import 'package:beautiful_demo/common/manager/websocket.dart';
import 'package:beautiful_demo/mvc/chat/list/controller.dart';
import 'package:beautiful_demo/mvc/home/market/controller.dart';
import 'package:beautiful_demo/mvc/user/login/controller.dart';
import 'package:drive/drive.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';

import 'home/controller.dart';
import 'home/mine/controller.dart';
import 'view.dart';
import 'package:flutter_mvc/flutter_mvc.dart';

///Description:主页
///Author:teihideharu
class MainController extends BaseController with WidgetsBindingObserver {
  List<BaseController> childrenController=[];
  final tabController=MvcTabController();

  int tips=0;
   
   MainController():super(MainPage());
   
   @override
   void initState(){
       super.initState();
       childrenController=[
         HomeController(),MarketController(),ChatListController(this),MineController(this),
       ];
       WidgetsBinding.instance.addObserver(this);
   }

   @override
  void dispose() {
    super.dispose();

    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if(state==AppLifecycleState.resumed){
      WebSocketManager.instance.onResume();
    }else if(state==AppLifecycleState.paused){
      WebSocketManager.instance.onPause();
    }
  }

   void onTabItemClick(int i) async {
     if(i<2){
       tabController.animToPage(i);
     }else{
       if(!UserManager.instance.isLogin){
         await LoginController().push(context);
         if(!UserManager.instance.isLogin){
           return;
         }
       }

       tabController.animToPage(i);
     }
     setState();
   }

  DateTime lastPopTime;
  void onWillListener() {
    if (tabController.index != 0) {
      onTabItemClick(0);
      setState(() {});
    } else if (lastPopTime == null ||
        DateTime.now().difference(lastPopTime) > const Duration(seconds: 2)) {
      lastPopTime = DateTime.now();
      ToastUtils.show('再按一次返回键退出应用');
    } else {
      // 退出app
      SystemNavigator.pop();
    }
  }

  void setTips(int tips) {
    this.tips=tips;
    setState();
  }
   
}
